<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\Config;
use app\common\model\game\Record;
use app\common\model\MoneyLog;
use think\Db;
use think\Exception;

class Club extends Api
{
    protected $noNeedLogin = "";
    protected $noNeedRight = "*";

    public function operation()
    {
        $params = $this->request->param();
        $club_info = \app\common\model\user\Club::where('user_id', $this->auth->id)->find();
        if (!$club_info) {
            $club_info = new \app\common\model\user\Club();
            $club_info->user_id = $this->auth->id;
        }

        foreach ($params as $key => $value) {
            $club_info->$key = $value;
        }

        $result = $club_info->allowField(true)->save();
        if ($result) {
            $this->success();
        }
        $this->error("修改失败");
    }

    public function info()
    {
        if ($this->auth->is_club != 1) {
            $this->error("请升级成为俱乐部后操作");
        }
        $club_info = \app\common\model\user\Club::where('user_id', $this->auth->id)->find();

        if (!$club_info) {
            $this->error("俱乐部信息有误,请联系客服");
        }

        $user_column = \app\common\model\User::where('parent_id', $this->auth->id)->where(["status" => "normal"])->column('id');
        array_push($user_column, $this->auth->id);
        $all_user = \app\common\model\User::where('parent_id', 'in', $user_column)->where(["status" => "normal"])->column('id');
        $tank_num = Db::name('game_record')->group("user_id")
            ->where(["user_id" => ["in", $all_user]])->count();
        $info = [
            'id' => $club_info['id'],
            'create' => date('Y-m-d H:i:s', $club_info['createtime']),
            'club_name' => $this->auth->club_name,
            'avatar' => $this->auth->avatar,
            'players_all' => count($all_user),
            'take_num' => $tank_num,
        ];
        $this->success("", $info);
    }

    public function statement()
    {
        $time = $this->request->param("time", 0);

        $where = [];
        $length = strlen($time);
        if ($time != 0) {
            $begin = strtotime($time);
            if ($length == 10) {
                $where["createtime"] = ["between", [$begin, $begin + 86400]];
            }

            if ($length == 7) {
                $where["createtime"] = ["between", [$begin, strtotime("next month", $begin)]];
            }
        }

        $one_user_ids = \app\common\model\User::parent_col([$this->auth->id], [], 1);
        $two_user_ids = \app\common\model\User::parent_col($one_user_ids, [], 1);
        $all_user_ids = \app\common\model\User::parent_col([$this->auth->id], [], 2);

        $service_one = Record::where(['user_id' => ['in', $one_user_ids]])->sum('one');
        $service_two = Record::where(['user_id' => ['in', $two_user_ids]])->sum('two');


        $add_player = Db::name('user')->where('parent_id', $this->auth->id)->where($where)->column('id');//新增
        $take_user_num = Db::name('game_record')->group("user_id")->where(["user_id" => ["in", $all_user_ids]])->where($where)->count();//当天参数人数
        $take_num = Db::name('game_record')->group("user_id")->where(["user_id" => ["in", $all_user_ids]])->where($where)->count();//当天参数次数
        $service = bcadd($service_one, $service_two, 2);

        $vip_num = Db::name('user_vip_log')->group("user_id")->where(["user_id" => ["in", $one_user_ids]])->where($where)->count();

        $vip_divide = Db::name('user_diamond_log')->where(["user_id" => ['in', $one_user_ids], "type" => 5])->where($where)->sum("diamond");

        $two_club = Db::name('user')->where('parent_id', $this->auth->id)
            ->where('is_club', 1)->where($where)->column('id');//子俱乐部

        $two_club_take_num = Db::name('game_record')->group("user_id")
            ->where(["user_id" => ["in", $two_club]])->where($where)->count();//当天参数次数
        $two_club_service = Record::where(['user_id' => ['in', $two_club]])->where($where)->sum('two');


        $level_list = Db::name('game_levels')->order('money ASC')->select();
        $level_array = [];
        foreach ($level_list as $value) {
            $level_where = [
                'level_id' => $value['id'],
                'user_id' => ['in', $all_user_ids]
            ];
            $level_num = Db::name('game_record')->where($level_where)->where($where)->count();
            $level_array[] = [
                'money' => $value['money'],
                'num' => $level_num,
                'ratio' => $take_num == 0 ? 0 : bcdiv($level_num, $take_num, 2)
            ];
        }
        $info = [
            'info' => [
                'add_player' => count($add_player),
                'take_user_num' => $take_user_num,
                'take_num' => $take_num,
                'service' => $service,
                'vip_num' => $vip_num,
                'vip_divide' => $vip_divide,
                'club_num' => count($two_club),
                'club_take_num' => $two_club_take_num,
                'club_service' => $two_club_service
            ],
            'level' => [
                $level_array
            ]
        ];

        $this->success("", $info);
    }

    public function player_log()
    {
        $name = $this->request->param("name", "");
        $pagesize = $this->request->param("size", 10);
        $child = \app\common\model\User::parent_col($this->auth->id, [], 1);
        $where = [];
        $id = \app\common\model\User::where("nickname", "LIKE", $name)->where("id", "in", $child)->column("id");
        if ($id && !empty($name)) {
            $where['gr.user_id'] = $id;
        }

        $lists = Db::name('game_record')->alias('gr')
            ->join("user u", "u.id = gr.user_id")
            ->join("game_lists gl", "gl.id = gr.game_id")
            ->join("game_modes gm", "gm.id = gr.mode_id")
            ->where(["gr.user_id" => ["in", $child]])->where($where)
            ->field("gr.*,u.nickname,gl.name as game_name,gm.name as mode_name,gr.rank as rank_num")->paginate($pagesize);

//        Record::where(["user_id" => ["in", $child]])->where($where)->paginate();
//        $this->success("", [
//            ['id' => 1, 'nickname' => 111, 'game_name' => '金铲铲', 'mode_name' => '狂暴模式', 'rank_num' => 2]
//        ]);
        $this->success("", $lists);
    }

    public function collect()
    {
        $type = $this->request->param("type", 1);
        $name = $this->request->param("name", "");
        $size = $this->request->param("size", 10);
        $where = [];

        switch ($type) {
            case 1:
                $ids = \app\common\model\User::where(['parent_id' => $this->auth->id, 'is_club' => 1, 'status' => 'normal'])->column('id');
                if (!empty($name)) {
                    $where['club_name'] = ['LIKE', $name];
                }
                break;
            case 2:
                $ids = \app\common\model\User::where(['parent_id' => $this->auth->id, 'is_club' => 0, 'status' => 'normal'])->column('id');
                if (!empty($name)) {
                    $where['nickname'] = ['LIKE', $name];
                }
                break;
            default:
                $this->error("选择有误");
        }

        if (!empty($name)) {
            $where['club_name'] = ['LIKE', $name];
        }

        $field = "id,club_name,club_time,createtime";
        $list = \app\common\model\User::where('id', "IN", $ids)->where($where)->field($field)
            ->paginate($size)->each(function ($items) use ($type) {
                $time = $type == 1 ? $items->club_time : $items->createtime;
                $items->club_id = Db::name('user_club')->where("user_id", $items->id)->value("id");
                $items->club_time = date('Y-m-d', $time);
                $items->type = $type;
                $parent_ids = Db::name('user')->where(['parent_id' => $items->id, 'status' => 'normal'])->column('id');
                $take_user_num = 0;
                $take_num = 0;
                $take_earnings = 0;
                if ($parent_ids) {
                    $take_user_num = Db::name('game_record')->group('user_id')->where(['id' => ['in', $parent_ids]])->count();
                    $take_num = Db::name('game_record')->where(['id' => ['in', $parent_ids]])->count('two');
                    $take_earnings = Db::name('game_record')->where(['id' => ['in', $parent_ids]])->sum('two');
                }
                $items->take_user_num = $take_user_num;
                $items->take_num = $take_num;
                $items->take_earnings = $take_earnings;
            });

        $this->success("", $list);
    }

    public function agent()
    {
        $user = $this->auth->getUser();
        if ($user['club_id'] != 0) {
            $this->error("当前身份已无需申请代理");
        }
        $money = Config::where("name", "agent_fee")->value('value', 0);
        if ($money > $user['money']) {
            $this->error("余额不足");
        }

        Db::startTrans();
        try {
            if ($money > 0) {
                $before = $user['money'];
                $after = bcadd($user['money'], -$money, 2);
                $user->save(['money' => $after, 'club_id' => 1]);
                MoneyLog::create([
                    'user_id' => $user['id'], 'money' => -$money,
                    'before' => $before, 'after' => $after,
                    'memo' => "开通代理", 'type' => 10
                ]);
                Db::commit();
            }
        } catch (Exception $exception) {
            Db::rollback();
            $this->error($exception->getMessage());
        }
        $this->success();
    }
}